import yaml
from PIL import Image, ImageTk
import tkinter as tk


def load_config(config_path):
    """加载 YAML 配置文件"""
    with open(config_path, "r") as file:
        return yaml.safe_load(file)


def pixel_to_gps(x, y, config, scale_factor, offset):
    """将像素位置转换为经纬度，考虑缩放比例和偏移量"""
    top_left_lon = config["large_rectangle"]["top_left"]["longitude"]
    top_left_lat = config["large_rectangle"]["top_left"]["latitude"]
    gps_per_pixel = config["large_rectangle"]["gps_per_pixel"] / scale_factor  # 缩放后每像素对应的经纬度跨度

    # 考虑拖拽偏移量
    adjusted_x = x - offset[0]
    adjusted_y = y - offset[1]

    # 计算经纬度
    longitude = top_left_lon + (adjusted_x - config["image_size"][0] // 2) * gps_per_pixel
    latitude = top_left_lat - (adjusted_y - config["image_size"][1] // 2) * gps_per_pixel
    return longitude, latitude


def on_click(event, config, scale_factor, offset):
    """鼠标点击事件处理函数"""
    x, y = event.x, event.y
    longitude, latitude = pixel_to_gps(x, y, config, scale_factor, offset)
    print(f"Clicked at pixel ({x}, {y}) -> GPS: Longitude={longitude}, Latitude={latitude}")


def zoom(event, canvas, img_tk, scale_factor, offset):
    """缩放功能，通过鼠标滚轮调整"""
    if event.delta > 0:
        scale_factor[0] *= 1.1  # 放大
    elif event.delta < 0:
        scale_factor[0] *= 0.9  # 缩小
    # 确保缩放比例有下限
    scale_factor[0] = max(0.1, min(scale_factor[0], 10))

    # 更新图像
    resized_img = img_tk.resize((int(img_tk.width * scale_factor[0]), int(img_tk.height * scale_factor[0])))
    canvas.img_tk = ImageTk.PhotoImage(resized_img)

    # 更新显示
    canvas.itemconfig(canvas.image_id, image=canvas.img_tk)
    canvas.configure(scrollregion=canvas.bbox("all"))


def start_drag(event, drag_data):
    """记录拖拽起始点"""
    drag_data["start_x"] = event.x
    drag_data["start_y"] = event.y


def drag(event, canvas, drag_data, offset):
    """拖拽地图"""
    # 计算偏移量
    dx = event.x - drag_data["start_x"]
    dy = event.y - drag_data["start_y"]
    drag_data["start_x"] = event.x
    drag_data["start_y"] = event.y

    # 更新偏移量
    offset[0] += dx
    offset[1] += dy

    # 移动画布内容
    canvas.move(canvas.image_id, dx, dy)


def main():
    # 加载图像和配置
    image_path = "output_with_polygon.pgm"
    config_path = "config.yaml"

    config = load_config(config_path)
    img = Image.open(image_path)

    # 使用 Tkinter 创建窗口
    root = tk.Tk()
    root.title("地图查看器")

    # 设置初始缩放比例和偏移量
    scale_factor = [1.0]
    offset = [0, 0]

    # 拖拽相关数据
    drag_data = {"start_x": 0, "start_y": 0}

    # 将图像加载到 Tkinter 界面
    img_tk = ImageTk.PhotoImage(img)
    canvas = tk.Canvas(root, width=img_tk.width(), height=img_tk.height())
    canvas.pack(fill=tk.BOTH, expand=True)

    # 显示图像
    canvas.img_tk = img_tk
    canvas.image_id = canvas.create_image(offset[0], offset[1], anchor=tk.NW, image=img_tk)

    # 绑定鼠标点击事件
    canvas.bind("<Button-1>", lambda event: on_click(event, config, scale_factor[0], offset))

    # 绑定鼠标滚轮事件（缩放功能）
    canvas.bind("<MouseWheel>", lambda event: zoom(event, canvas, img, scale_factor, offset))

    # 绑定拖拽事件
    canvas.bind("<ButtonPress-2>", lambda event: start_drag(event, drag_data))  # 中键按下开始拖拽
    canvas.bind("<B2-Motion>", lambda event: drag(event, canvas, drag_data, offset))  # 中键移动拖拽

    # 启动 Tkinter 主循环
    root.mainloop()


if __name__ == "__main__":
    main()
